package com.miage.kangourou.server.dao.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.miage.kangourou.client.beans.TypeEvenement;

public class TypeEvenementDao extends GenericDao<TypeEvenement> {

	public TypeEvenementDao(Connection connect) {
		super(connect);
	}

	public TypeEvenement findById(int id) throws SQLException {
		ResultSet result = connect.createStatement(
				ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)
				.executeQuery("SELECT * FROM TYPE_EVT WHERE ID_TYPE = " + id);

		TypeEvenement evt;

		if (result.next()) {
			evt = new TypeEvenement(result.getInt("ID_TYPE"), result
					.getString("TYPE_EVT"), result.getString("COMMENTAIRE"));
		} else {
			evt = new TypeEvenement();
		}

		result.close();

		return evt;
	}

	public List<TypeEvenement> findAll() throws SQLException {
		ResultSet result = connect.createStatement(
				ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)
				.executeQuery("SELECT * FROM TYPE_EVT");

		List<TypeEvenement> all = new ArrayList<TypeEvenement>();
		while (result.next()) {
			all.add(new TypeEvenement(result.getInt("ID_TYPE"), result
					.getString("TYPE_EVT"), result.getString("COMMENTAIRE")));
		}

		result.close();

		return all;
	}

	public void create(TypeEvenement evt) throws SQLException {
		if (evt instanceof TypeEvenement && !evt.equals(null)) {

			connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY).executeQuery(
					"INSERT INTO TYPE_EVT (ID_TYPE, TYPE_EVT, COMMENTAIRE) VALUES ("
							+ evt.getId_type() + ", \""
							+ evt.getTypeEvenement() + "\", \""
							+ evt.getCommentaire() + "\")");
		}
	}

	public boolean alreadyExist(TypeEvenement evt) throws SQLException {
		boolean exist = false;

		if (evt instanceof TypeEvenement && !evt.equals(null)) {

			ResultSet result = connect.createStatement(
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY)
					.executeQuery(
							"SELECT * FROM TYPE_EVT WHERE ID_TYPE= "
									+ evt.getId_type());

			if (result.next()) {
				exist = true;
			}

			result.close();
		}

		return exist;
	}

	public boolean delete(int idTypeEvt) {
		boolean deleted = true;

		try {
			connect.createStatement(
						ResultSet.TYPE_SCROLL_INSENSITIVE,
						ResultSet.CONCUR_READ_ONLY).executeQuery(
						"DELETE FROM TYPE_EVT WHERE ID_TYPE = " + idTypeEvt);

		} catch (SQLException e) {
			e.printStackTrace();
			deleted = false;
		}

		

		return deleted;
	}

}
